import React, { useEffect, useState } from "react";
import { FieldChangeData, LCGUI } from "../../../json-schema/LCGUI";
import { Control } from "../../../json-schema/SchemaTypes";
import { IotTempHumController } from "./IotTempHumController";
import { ConfigType } from "../../../designer/right/ConfigContent";
import { ApiFacility } from "_common/api/iot";
import { IotDevice } from "_common/entity";
import { useAxios, useFacility } from "components";

export const IotTempHumDeviceConfig: React.FC<
  ConfigType<IotTempHumController>
> = ({ controller }) => {
  const { device, base } = controller.getConfig()!;
  const [deviceList, setDeviceList] = useState<IotDevice[]>([]);
  const [deviceCode, setDeviceCode] = useState<string>();
  const axios = useAxios();
  const facilityId = useFacility();
  useEffect(() => {
    if (axios && facilityId) {
      const apiFacility = new ApiFacility(axios!);
      apiFacility.getFacilityDevice(Number(facilityId)).then((res) => {
        setDeviceList(res.data?.filter((a) => a.dtCode == base?.code));
      });
    }
  }, [axios, facilityId]);

  const onFieldChange = (fieldChangeData: FieldChangeData) => {
    const { dataFragment, dataKeyPath } = fieldChangeData;
    if (dataKeyPath?.[1] === "search") {
      let searchValue = (dataFragment as any)["search"];
      setDeviceCode(searchValue);
      return;
    }
    // 安装位置赋值
    if (dataKeyPath?.[1] === "deviceCode") {
      let code = (dataFragment as any).device?.deviceCode;
      let name = deviceList.find((a) => a.deviceCode == code)?.deviceName;
      controller.update({
        device: {
          position: name,
        } as any,
      });
    }
    controller.update(dataFragment!);
  };

  console.log("device:", device);

  const schema: Control = {
    type: "grid",
    config: { columns: 1 },
    key: "device",
    children: [
      {
        key: "position",
        type: "input",
        label: "已绑定设备",
        value: device?.deviceCode,
        config: { disabled: true },
      },
      {
        key: "search",
        type: "input",
        label: "搜索设备",
        value: deviceCode,
        config: {
          placeholder: "请输入设备ID",
        },
      },
      {
        key: "deviceCode",
        type: "select",
        label: "温湿度设备",
        value: device?.deviceCode,
        config: {
          options: deviceList
            ?.filter((a) => {
              if (deviceCode && deviceCode != "" && deviceCode != undefined) {
                return a.deviceCode
                  ? a.deviceCode.toString().indexOf(deviceCode) > 0
                  : false;
              } else {
                return a;
              }
            })
            .map((a) => {
              return {
                label: `(${a.deviceCode})-${a.deviceName!}`,
                value: a.deviceCode!,
              };
            }) as [],
        },
      },
    ],
  };

  return <LCGUI schema={schema} onFieldChange={onFieldChange} />;
};
